import {DatePicker, Divider, notification, Select} from 'antd'
import React, { useState, useRef, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, history } from 'umi'
import { getCompanyListAuth, getSecurityBatch } from '../../service'
import { getSecurityBatchGroupList } from './service'
import moment from 'moment'
import CreateTable from './components/CreateTable'
import { exportSecurityRecord } from '@/pages/Security/SocialSecurityPlan/service'

const { Option } = Select

const TableList = () => {
  const actionRef = useRef()
  const [visible, setVisible] = useState(false)
  const [current, setCurrent] = useState(null)
  const [contractData, setContractData] = useState(null)

  useEffect(() => {
    getCompanyListAuth().then(res => {
      if(res.flag){
        res && setContractData(res.data)
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
    })
  }, [])

  const columns = [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`,
      hideInSearch: true,
    },
    {
      title: '日期',
      dataIndex: 'time',
      renderFormItem: (item, props) => {
        return <DatePicker defaultValue={moment(new Date(), 'YYYY-MM')} {...props} picker="month"/>
      },
      hideInTable: true,
    },
    {
      title: '参保单位',
      dataIndex: 'unitName',
      renderFormItem: (item, props) => {
        console.log(contractData)
        return <Select placeholder="请选择参保单位" showSearch allowClear
                       filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
          {contractData.length > 0 ? contractData.map((item, index) => {
            return (
              <Option value={item.name} key={index} lable={item}>
                {item.name}
              </Option>
            )
          }) : ''}
        </Select>
      },
    },
    {
      title: '参保地',
      dataIndex: 'cityName',
      hideInSearch: true,
    },
    {
      title: '企业缴纳',
      dataIndex: 'orgCost',
      hideInSearch: true,
    },
    {
      title: '个人缴纳',
      dataIndex: 'personCost',
      hideInSearch: true,
    },
    {
      title: '总计',
      dataIndex: 'totalCost',
      hideInSearch: true,
    },
    {
      title: '参保人数',
      dataIndex: 'number',
      hideInSearch: true,
    },
    {
      title: '操作人',
      dataIndex: 'applyer',
      hideInSearch: true,
    },
    {
      title: '汇缴期',
      dataIndex: 'operateTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM') : ''
      }
    },
    {
      title: '确认日期',
      dataIndex: 'confirmTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      render: (item, record) => (
        <>
          {<a onClick={() => showDetails(record)}>查看详情</a>}
          {<Divider type="vertical"/>}
          {<a onClick={() => exportExcel(record)}>导出参保明细</a>}
        </>
      ),
    },
  ]

  const showDetails = (record) => {
    setVisible(true)
    setCurrent(record)
  }

  const exportExcel = (data) => {
    getSecurityBatchGroupList(data.id).then(result => {
      exportSecurityRecord(result.map(item => item.recordId)).then(res => {
        let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const objectUrl = window.URL.createObjectURL(blob)
        let a = document.createElement('a')
        a.href = objectUrl //指定下载链接
        a.download = '社保参保明细.xlsx' //指定下载文件名
        a.click() //触发下载
        a.remove() //除a标签
        window.URL.revokeObjectURL(objectUrl) //释放
      })
    })
  }

  const onCancel = () => {
    setCurrent(null)
    setVisible(false)
  }

  return (
    <PageHeaderWrapper>
      {
        contractData && <ProTable
          actionRef={actionRef}
          rowKey="id"
          request={(params) => getSecurityBatch(params, 0)}
          columns={columns}
        />
      }
      <CreateTable
        visible={visible}
        current={current}
        onCancel={onCancel}
      />
    </PageHeaderWrapper>
  )
}

export default connect(({}) => ({}))(TableList)
